import { BasedbService } from './basedb';

class TagdbService extends BasedbService {
  tableName: string;
  constructor() {
    super({
      dbname: 'sqlite-tag.db'
    });
    this.tableName = 'tag';
    this.initTable();
  }

  /*
   * 初始化表
   */
  private initTable(): void {
    // 检查表是否存在
    const masterStmt = this.db.prepare(
      'SELECT * FROM sqlite_master WHERE type=? AND name = ?'
    );
    let tableExists = masterStmt.get('table', this.tableName);
    if (!tableExists) {
      // 创建表
      const create_table_sql = `CREATE TABLE ${this.tableName}
        (
           id INTEGER PRIMARY KEY AUTOINCREMENT,
           tag CHAR(200) NOT NULL
        );`;
      this.db.exec(create_table_sql);
    }
  }

  /*
   * 添加标签 (sqlite)
   */
  addTag(tag) {
    const insert = this.db.prepare(
      `INSERT INTO ${this.tableName} (tag) VALUES (@tag)`
    );
    insert.run({ tag });
    return true;
  }

  /*
   * 查询tag表所有数据 (sqlite)
   */
  queryAllTag() {
    const selectAllUser = this.db.prepare(`SELECT * FROM ${this.tableName} `);
    return selectAllUser.all();
  }

  /*
   * 删除tag表中指定条件的数据 (sqlite)
   */
  deleteTag(id: number) {
    const delUser = this.db.prepare(
      `DELETE FROM ${this.tableName} WHERE id = ?`
    );
    delUser.run(id);
    return true;
  }
}

TagdbService.toString = () => '[class TagdbService]';
const tagdbService = new TagdbService();

export { TagdbService, tagdbService };
